<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Infotech Ltd.
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: mslaria $ ($Date: 2007/07/26 07:38:48 $)
// $RCSfile: functions_ticketcore.php,v $ : $Revision: 1.32 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

require_once ("./modules/tickets/tickets.php");
require_once ("./modules/tickets/functions_search.php");

echo $test;

/**
* Merge multiple tickets into a single ticket
*/
function mergeTickets($parentticketid, $ticketidlist)
{
	global $dbCore, $_SWIFT;

	if (!_is_array($ticketidlist))
	{
		return false;
	}

	$_ticketobj =& new TicketMain($parentticketid, true);
	if (!$_ticketobj->ticket)
	{
		return false;
	}

	// Now get the ticketmasks for the to be merged tickets...
	$_ticketmaskidlist = $_ticketidlist = $departmentidlist = array();
	$_mergeemaillist = array();

	$departmentidlist[] = $_ticketobj->ticket["departmentid"];
	$dbCore->query("SELECT `ticketid`, `ticketmaskid`, `departmentid`, `email` FROM `". TABLE_PREFIX ."tickets` WHERE `ticketid` IN (". buildIN($ticketidlist) .");");
	while ($dbCore->nextRecord())
	{
		$_ticketmaskidlist[$dbCore->Record["ticketid"]] = $dbCore->Record["ticketmaskid"];
		$_ticketidlist[] = $dbCore->Record["ticketid"];
		if (!in_array($dbCore->Record["departmentid"], $departmentidlist))
		{
			$departmentidlist[] = $dbCore->Record["departmentid"];
		}

		if ($dbCore->Record["email"] != $_ticketobj->ticket["email"] && !in_array($dbCore->Record["email"], $_mergeemaillist))
		{
			$_mergeemaillist[] = $dbCore->Record["email"];
		}
	}

	// First mark all the replies under different tickets to the parent ticket
	$dbCore->query("UPDATE `". TABLE_PREFIX ."ticketposts` SET `ticketid` = '". intval($parentticketid) ."' WHERE `ticketid` IN (". buildIN($_ticketidlist) .");");

	// Now update all the audit logs
	$dbCore->query("UPDATE `". TABLE_PREFIX ."auditlogs` SET `departmentid` = '". intval($_ticketobj->ticket["departmentid"]) ."', `ticketid` = '". intval($parentticketid) ."' WHERE `ticketid` IN (". buildIN($_ticketidlist) .");");

	// Attachments
	$dbCore->query("UPDATE `". TABLE_PREFIX ."attachments` SET `ticketid` = '". intval($parentticketid) ."' WHERE `ticketid` IN (". buildIN($_ticketidlist) .");");

	// Ticket notes
	$dbCore->query("UPDATE `". TABLE_PREFIX ."ticketnotes` SET `typeid` = '". intval($parentticketid) ."' WHERE `typeid` IN (". buildIN($_ticketidlist) .") AND `notetype` = '". NOTE_TICKET ."';");

	// Recipients
	$dbCore->query("UPDATE IGNORE `". TABLE_PREFIX ."ticketrecipients` SET `ticketid` = '". intval($parentticketid) ."' WHERE `ticketid` IN (". buildIN($_ticketidlist) .");");

	// Ticket Time Tracking Entries
	$dbCore->query("UPDATE `". TABLE_PREFIX ."tickettimetrack` SET `ticketid` = '". intval($parentticketid) ."' WHERE `ticketid` IN (". buildIN($_ticketidlist) .");");

	// Add all recipients
	if ($_SWIFT["settings"]["t_mergrecip"] == 1)
	{
		$_ticketobj->addRecipients($_mergeemaillist, RECIPIENT_CCUSER);
	}

	// Recount!
	$_ticketobj->updateTicketProperties();

	// Insert the entry into merge logs
	$_msql = array();
	foreach ($_ticketidlist as $key=>$val)
	{
		$_ticketobj->addAuditLogEntry(LOG_STAFF, ACTION_MERGE, sprintf($_SWIFT["language"]["al_merge"], $val));
		$_msql[] = "('". intval($val) ."', '". $dbCore->escape($_ticketmaskidlist[$val]) ."', '". intval($parentticketid) ."', '". intval($_SWIFT["staff"]["staffid"]) ."', '". DATENOW ."')";
	}
	if (count($_msql))
	{
		$dbCore->query("INSERT INTO `". TABLE_PREFIX ."ticketmergelog` (`oldticketid`, `oldticketmaskid`, `ticketid`, `staffid`, `dateline`) VALUES ". implode(",", $_msql) .";");
	}
	
	if(!in_array($parentticketid, $_ticketidlist))
	{
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."tickets` WHERE `ticketid` IN (". buildIN($_ticketidlist) .");");
	}

	rebuildTicketCountCache($departmentidlist);

	return true;
}


/**
* Recounts the ticket departments
*/
function recountTicketDepartments()
{
	global $_SWIFT;

	if (count($_SWIFT["recountdep"]))
	{
		rebuildTicketCountCache($_SWIFT["recountdep"]);
	}
}

/**
* Mass Print Tickets
*/
function massPrintTickets($ticketidlist)
{
	global $template, $dbCore, $_SWIFT;

	$template->assign("documenttitle", $_SWIFT["settings"]["general_companyname"]);
	echo $template->displayTemplate("header.tpl");

	if (!_is_array($ticketidlist))
	{
		return false;
	}

	require_once ("./modules/tickets/functions_ticketmain.php");

	$_ticketobjlist = array();
	$index = 0;
	foreach ($ticketidlist as $key=>$val)
	{
		$_ticketobj =& new TicketMain($val, iif(empty($escalationruleid), true, false), iif(empty($escalationruleid), LOG_STAFF, LOG_ESCALATION));

		$_ticketobj->printTicket();
	}
}

/**
* Use it to update ticket status collectively.. 
*/
function updateTicketStatus($ticketidlist, $depcheck = true, $ownerstaffid = false, $departmentid = false, $ticketstatusid = false, $priorityid = false, $flagtype = false, $escalationruleid = false)
{
	global $dbCore, $_SWIFT;

	if (!_is_array($ticketidlist))
	{
		return false;
	}

	require_once ("./modules/tickets/functions_ticketmain.php");

	$_ticketobjlist = $departmentidlist = $_escalationpaths = array();
	$index = 0;
	foreach ($ticketidlist as $key=>$val)
	{
		$_ticketobjlist[$index] =& new TicketMain($val, iif(empty($escalationruleid), true, false), iif(empty($escalationruleid), LOG_STAFF, LOG_ESCALATION));
		$_ticketobj = &$_ticketobjlist[$index];
		$_ticketobj->norecount = true;
		
		
		
		if ($_ticketobj->ticket)
		{
			if ($_SWIFT["staff"]["tcanviewall"] != 1 && $_ticketobj->ticket["ownerstaffid"] != $_SWIFT["staff"]["staffid"])
			{
				// do nothing...
			} else {
			
				$recountdepartent = false;
				$_cansla = false;

				// ======= HANDLE ESCALATION PATHS =======
				if (!empty($escalationruleid))
				{
					$_escalationpaths[] = "('". DATENOW ."', '". intval($_ticketobj->ticket["ticketid"]) ."', '". intval($_ticketobj->ticket["slaplanid"]) ."', '". intval($escalationruleid) ."', '". intval($_ticketobj->ticket["ownerstaffid"]) ."', '". intval($_ticketobj->ticket["departmentid"]) ."', '". intval($_ticketobj->ticket["ticketstatusid"]) ."', '". intval($_ticketobj->ticket["priorityid"]) ."', '". intval($_ticketobj->ticket["flagtype"]) ."')";
				}

				// ======= UPDATE OWNER =======
				if ((string)$ownerstaffid != "")
				{
					$_ticketobj->assignTicket($ownerstaffid);
				}

				// ======= UPDATE DEPARTMENT =======
				if (!empty($departmentid))
				{
					if (!in_array($_ticketobj->ticket["departmentid"], $departmentidlist))
					{
						$departmentidlist[] = $_ticketobj->ticket["departmentid"];
					}

					$_ticketobj->moveTicket($departmentid);

					if (!in_array($departmentid, $departmentidlist))
					{
						$departmentidlist[] = $departmentid;
					}

					$_cansla = true;
				}

				// ======= UPDATE TICKET STATUS =======
				if (!empty($ticketstatusid))
				{
					$_ticketobj->changeStatus($ticketstatusid);
					if (!in_array($_ticketobj->ticket["departmentid"], $departmentidlist))
					{
						$departmentidlist[] = $_ticketobj->ticket["departmentid"];
					}

					$_cansla = true;
				}

				// ======= UPDATE TICKET PRIORITY =======
				if (!empty($priorityid))
				{
					$_ticketobj->changePriority($priorityid);

					$_cansla = true;
				}

				// ======= FLAG TYPE =======
				// Flag
				$_flagtype = substr($flagtype, 0, 2);
				$_flagvalue = intval(substr($flagtype, 2));

				if ($_flagtype == "f_")
				{
					if (!empty($_flagvalue))
					{
						$_ticketobj->flagTicket($_flagvalue);
					} else if ($_flagvalue == "0") {
						$_ticketobj->clearFlag();
					}

				// Label
				} else if ($_flagtype == "l_") {
					$_ticketobj->insertTicketLabelLink($_flagvalue);
				}

				// ======= ESCALATION RULE? =======
				if (!empty($escalationruleid))
				{
					$_ticketobj->escalateTicket($escalationruleid, $_cansla);
				}
			}
		}
		$index++;
	}

	if (count($departmentidlist))
	{
		$_SWIFT["recountdep"] = $departmentidlist;
		register_shutdown_function("recountTicketDepartments");
	}

	if (count($_escalationpaths))
	{
		$dbCore->query("INSERT INTO `". TABLE_PREFIX ."escalationpaths` (`dateline`, `ticketid`, `slaplanid`, `escalationruleid`, `ownerstaffid`, `departmentid`, `ticketstatusid`, `priorityid`, `flagtype`) VALUES ". implode(",", $_escalationpaths).";");
	}

	return true;

/*	// First get the departments from all the tickets
	$_ticketidlist = $departmentidlist = $ticketstatusidlist = $_auditlogsql = $_auditcache = array();
	if ($depcheck == true)
	{
		$_assigns = getAssignedDepartments(MODULE_TICKETS);
	}

	if ($escalationruleid)
	{
		$logtype = LOG_ESCALATION;
		$auditstaffid = 0;
	} else {
		$logtype = LOG_STAFF;
		$auditstaffid = $_SWIFT["staff"]["staffid"];
	}

	$auditindex = 0;
	$dbCore->query("SELECT `ticketid`, `departmentid`, `ticketstatusid`, `userid`, `ownerstaffid` FROM `". TABLE_PREFIX ."tickets` WHERE `ticketid` IN (". buildIN($ticketidlist) .");");
	while ($dbCore->nextRecord())
	{
		if ($depcheck == true && in_array($dbCore->Record["departmentid"], $_assigns))
		{
			$_ticketidlist[] = $dbCore->Record["ticketid"];
		} else if ($depcheck == false) {
			$_ticketidlist[] = $dbCore->Record["ticketid"];
		}

		$_auditcache[$auditindex]["log"] = "('". intval($dbCore->Record["ticketid"]) ."', '". intval($auditstaffid) ."', '". $dbCore->escape($dbCore->Record["departmentid"]) ."', '". $dbCore->escape($dbCore->Record["userid"]) ."', '". DATENOW ."', '%s', '%s','%s')";
		$_auditcache[$auditindex]["ownerstaffid"] = intval($dbCore->Record["ownerstaffid"]);
		$_auditcache[$auditindex]["departmentid"] = intval($dbCore->Record["departmentid"]);
		$_auditcache[$auditindex]["priorityid"] = intval($dbCore->Record["priorityid"]);
		$_auditcache[$auditindex]["ticketstatusid"] = intval($dbCore->Record["ticketstatusid"]);

		// Fill up departments
		if (!in_array($dbCore->Record["departmentid"], $departmentidlist))
		{
			$departmentidlist[] = $dbCore->Record["departmentid"];
		}

		// Fill up ticket status
		if (!in_array($dbCore->Record["ticketstatusid"], $ticketstatusidlist))
		{
			$ticketstatusidlist[] = $dbCore->Record["ticketstatusid"];
		}
		$auditindex++;
	}

	$_sql = array();
	$recountstatus = $recountdep = false;

	// ======= CHANGE OWNER =======
	if ((string)$ownerstaffid != "")
	{
		if ($ownerstaffid == 0)
		{
			$_sql[] = "`assignstatus` = '0'";
		} else {
			$_sql[] = "`assignstatus` = '1'";
		}
		$_sql[] = "`ownerstaffid` = '". intval($ownerstaffid) ."'";
		foreach ($_auditcache as $key=>$val)
		{
			$currentowner = htmlspecialchars($_SWIFT["staffcache"][$val["ownerstaffid"]]["fullname"]);
			$newowner = htmlspecialchars($_SWIFT["staffcache"][$ownerstaffid]["fullname"]);
			$_auditlogsql[] = sprintf($val["log"], intval($logtype), ACTION_ASSIGN, sprintf($_SWIFT["language"]["al_owner"], iif(empty($val["ownerstaffid"]), $_SWIFT["language"]["unassigned"], $currentowner), iif(empty($ownerstaffid), $_SWIFT["language"]["unassigned"], $newowner)));
		}
	}

	// ======= CHANGE DEPARTMENT =======
	if (!empty($departmentid))
	{
		$_sql[] = "`departmentid` = '". intval($departmentid) ."'";

		foreach ($_auditcache as $key=>$val)
		{
			$_auditlogsql[] = sprintf($val["log"], intval($logtype), ACTION_MOVE, sprintf($_SWIFT["language"]["al_department"], $_SWIFT["departmentcache"][$val["departmentid"]]["title"], $_SWIFT["departmentcache"][$departmentid]["title"]));
		}

		if (!in_array($departmentid, $departmentidlist))
		{
			$departmentidlist[] = $departmentid;
		}
		$recountdep = true; // Recounts all ticket status under a department
	}

	// ======= CHANGE STATUS =======
	if (!empty($ticketstatusid))
	{
		$_sql[] = "`ticketstatusid` = '". intval($ticketstatusid) ."'";

		foreach ($_auditcache as $key=>$val)
		{
			$_auditlogsql[] = sprintf($val["log"], intval($logtype), ACTION_STATUS, sprintf($_SWIFT["language"]["al_status"], $_SWIFT["statuscache"][$val["ticketstatusid"]]["title"], $_SWIFT["statuscache"][$ticketstatusid]["title"]));
		}

		if (!in_array($ticketstatusid, $ticketstatusidlist))
		{
			$ticketstatusidlist[] = $ticketstatusid;
		}
		$recountstatus = true;
	}

	// ======= CHANGE PRIORITY =======
	if (!empty($priorityid))
	{
		$_sql[] = "`priorityid` = '". intval($priorityid) ."'";

		foreach ($_auditcache as $key=>$val)
		{
			$_auditlogsql[] = sprintf($val["log"], intval($logtype), ACTION_PRIORITY, sprintf($_SWIFT["language"]["al_priority"], $_SWIFT["prioritycache"][$val["priorityid"]]["title"], $_SWIFT["prioritycache"][$priorityid]["title"]));
		}

	}

	// ======= ESCALATION =======
	if (!empty($escalationruleid))
	{
		$_sql[] = "`escalationruleid` = '". intval($escalationruleid) ."'";
		$_sql[] = "`isescalated` = '1'";

		foreach ($_auditcache as $key=>$val)
		{
			$_auditlogsql[] = sprintf($val["log"], intval($logtype), ACTION_ESCALATION, sprintf($_SWIFT["language"]["al_escalated"], $_SWIFT["escalationrulecache"][$escalationruleid]["title"]));
		}
	}

	// ======= CARRY OUT THE ACTIONS =======
	if (count($_sql))
	{
		$dbCore->query("UPDATE `". TABLE_PREFIX ."tickets` SET ". implode(", ", $_sql) ." WHERE `ticketid` IN (". buildIN($_ticketidlist) .");");

		if (count($_auditlogsql))
		{
			$dbCore->query("INSERT INTO `". TABLE_PREFIX ."auditlogs` (`ticketid`, `staffid`, `departmentid`, `userid`, `dateline`, `logtype`, `actiontype`, `actionmsg`) VALUES ". implode(",", $_auditlogsql) .";");
		}
		rebuildTicketCountCache($departmentidlist);

	}*/
}

/**
* Marks the tickets as due
*/
function ticketsMarkAsDue($ticketidlist, $customtimeline = false)
{
	global $dbCore;

	if (!_is_array($ticketidlist))
	{
		return false;
	}

	if (!$customtimeline)
	{
		$customtimeline = DATENOW-1;
	}

	$dbCore->query("UPDATE `". TABLE_PREFIX ."tickets` SET `duetime` = '". intval($customtimeline) ."' WHERE `ticketid` IN (". buildIN($ticketidlist) .");");

	return true;
}

/**
* Added later to fix Message ID Issues with PHP CLI
*/
function getMessageLocalHost() 
{ 
	if (!empty($_SERVER['HTTP_HOST']))
	{
		return $_SERVER['HTTP_HOST'];
	}

	if (!empty($_SERVER['SERVER_NAME']))
	{
		return $_SERVER['SERVER_NAME'];
	}

	if (!empty($_SERVER['HOST']))
	{
		return $_SERVER['HOST'];;
	}

	return "localhost";
}

/**
* Create a new ticket
*/
function createTicket($posttype, $staffid, $userid, $fullname, $email, $subject, $contents, $ishtml, $priorityid, $ticketstatusid, $departmentid, $emailqueueid, $charset, $transferencoding, $tgroupid = false, $attachments = false, $isemailed = false, $sendautoresponder, $phoneno = false)
{
	global $dbCore, $_SWIFT;

	$ticketmaskid = generateTicketMask(); // Generate the unique ticket mask

	// Insert the Actual Record
	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."tickets` (`ticketmaskid`, `departmentid`, `ticketstatusid`, `priorityid`, `emailqueueid`, `userid`, `staffid`, `fullname`, `email`, `lastreplier`, `replyto`, `subject`, `dateline`, `lastactivity`, `laststaffreplytime`, `slaplanid`, `duetime`, `totalreplies`, `ipaddress`, `flagtype`, `hasnotes`, `hasattachments`, `isemailed`, `edited`, `editedbystaffid`, `editeddateline`, `creator`, `charset`, `transferencoding`, `tgroupid`, `isphonecall`, `phoneno`, `lastuserreplytime`) VALUES ('". $dbCore->escape($ticketmaskid) ."', '". intval($departmentid) ."', '". intval($ticketstatusid) ."', '". intval($priorityid) ."', '". intval($emailqueueid) ."', '". intval($userid) ."', '". intval($staffid) ."', '". $dbCore->escape($fullname) ."', '". $dbCore->escape($email) ."', '". $dbCore->escape($fullname) ."', '". $dbCore->escape($email) ."', '". $dbCore->escape($subject) ."', '". DATENOW ."', '". DATENOW ."', '0', '0', '0', '0', '". $dbCore->escape($_SERVER["REMOTE_ADDR"]) ."', '0', '0', '0', '". iif($isemailed==true, "1", "0") ."', '0', '0', '0', '". intval($posttype) ."', '". $dbCore->escape($charset) ."', '". $dbCore->escape($transferencoding) ."', '". intval($tgroupid) ."', '". iif($phoneno!=""||$phoneno=="-1", "1", "0") ."', '". iif($phoneno!=""&&$phoneno!="-1", $dbCore->escape($phoneno)) ."', '". DATENOW ."');");
	$ticketid = $dbCore->lastInsertId();
	if (!$ticketid)
	{
		return false;
	}

	// Load the ticket object.
	$_SWIFT["ticketobj"] =& new TicketMain($ticketid);
	$_ticket = &$_SWIFT["ticketobj"];
	if (_is_array($attachments))
	{
		$_ticket->alerts->addAttachments($attachments);
	}
	$_ticket->alerts->raiseAlert(ALERT_NEWTICKET, array("contentshtml" => getProcessedHTML($contents), "contentstext" => getProcessedText($contents), "contentssms" => substr($_ticket->returnProcessedContent($contents),0,40), "fullname" => $fullname));

	$_ticket->resetSLATimeline();

	if ($posttype == POST_STAFF)
	{
		$queuesignature = $_SWIFT["queuecache"]["list"][$emailqueueid]["contents"];
		$staffsignature = $_SWIFT["staff"]["signature"];
		$contents = preg_replace("#(\r\n|\r|\n)#s", SWIFT_CRLF, $contents).iif(!empty($staffsignature), SWIFT_CRLF.$staffsignature, iif(!empty($queuesignature), SWIFT_CRLF.$queuesignature));
	}

	// Create the Ticket Post
	$ticketpostresult = $_ticket->createTicketPost(true, $posttype, $userid, $staffid, $fullname, $email, "", $subject, $contents, $ishtml, $isemailed, $attachments);
	$ticketpostid = $ticketpostresult[0];
	$messageid = $ticketpostresult[1];

	$_ticket->updatesql[] = "`firstpostid` = '". intval($ticketpostid) ."'";

	// Add the Audit Log entry..
	if ($isemailed == true)
	{
		$logtype = LOG_PARSER;
	} else if ($posttype == POST_STAFF) {
		$logtype = LOG_STAFF;
	} else {
		$logtype = LOG_CLIENT;
	}
	$_ticket->addAuditLogEntry($logtype, ACTION_NEWTICKET, sprintf($_SWIFT["language"]["al_newticket"], htmlspecialchars($fullname)));

	// Raise the Alert
	$_ticket->loadTicketCustomFields();

	if ($sendautoresponder && !empty($email))
	{
		$_ticket->messageid = $messageid;
		$_ticket->sendAutoResponder();
	}

	return array($ticketid, $ticketmaskid, $ticketpostid, $messageid, &$this);
}

/**
* Generate a random Ticket Mask
*/
function generateTicketMask()
{
	global $dbCore, $_SWIFT;

	mt_srand ((double) microtime() * 1000000);
	$alpha1 = mt_rand(65,90);
	mt_srand ((double) microtime() * 1000000);
	$alpha2 = mt_rand(65,90);
	mt_srand ((double) microtime() * 1000000);
	$alpha3 = mt_rand(65,90);

	$alpha1 = chr($alpha1);
	$alpha2 = chr($alpha2);
	$alpha3 = chr($alpha3);

	// This was a serious issue in v2, The stupid computer would come up with words like GAY and client would be pissed as hell.
	$prefix = $alpha1.$alpha2.$alpha3;
	if (in_array(strtoupper($prefix), $_SWIFT["stopwords"]))
	{
		return generateTicketMask();
	}

	mt_srand ((double) microtime() * 1000000);
	$num = mt_rand(100000,999999);
	$ticketmaskid = $alpha1 . $alpha2 . $alpha3 . "-" . $num;

	$_maskcheck = $dbCore->queryFetch("SELECT ticketmaskid FROM `". TABLE_PREFIX ."tickets` WHERE `ticketmaskid` = '". $dbCore->escape($ticketmaskid) ."';");
	if (!empty($_maskcheck["ticketmaskid"]))
	{
		return generateTicketMask();
	}

	return $ticketmaskid;
}

/**
* Gets the Ticket Data From a Given Ticket Mask
*/
function getTicketIDFromMask($ticketmask)
{
	global $dbCore;

	$dbCore->query("SELECT `ticketid`, `ticketmaskid` FROM `". TABLE_PREFIX ."tickets` WHERE `ticketmaskid` = '". $dbCore->escape($ticketmask) ."';");
	$dbCore->nextRecord();
	if ($dbCore->Record["ticketmaskid"] == $ticketmask && trim($ticketmask) != "")
	{
		return $dbCore->Record["ticketid"];
	} else {
		return false;
	}
}

/**
* Checks to see if a ticket is merged, if yes, returns the merged ticket id, if not returns false
*/
function getMergedStatusFromID($ticketid)
{
	global $dbCore;

	$dbCore->query("SELECT `ticketid` FROM `". TABLE_PREFIX ."ticketmergelog` WHERE `oldticketid` = '". $dbCore->escape($ticketid) ."';");
	$dbCore->nextRecord();
	if (trim($dbCore->Record["ticketid"]) != "")
	{
		// Success!
		return $dbCore->Record["ticketid"];
	} else {
		return false;
	}
}

/**
* Get the Emails from given tickets and ban them.
*/
function banTickets($ticketidlist, $depcheck = false)
{
	global $dbCore, $_SWIFT, $module;

	if (!_is_array($ticketidlist))
	{
		return false;
	}

	if ($depcheck == true)
	{
		$_assigns = getAssignedDepartments(MODULE_TICKETS);
	}

	$emaillist = array();
	$dbCore->query("SELECT `ticketid`, `departmentid`, `email` FROM `". TABLE_PREFIX ."tickets` WHERE `ticketid` IN (". buildIN($ticketidlist) .");");
	while ($dbCore->nextRecord())
	{
		$doinsert = false;
		if (!in_array($dbCore->Record["email"], $emaillist))
		{
			if ($depcheck == true)
			{
				if (in_array($dbCore->Record["departmentid"], $_assigns))
				{
					$doinsert = true;
				}
			} else {
				$doinsert = true;
			}
			if ($doinsert)
			{
				$emaillist[] = $dbCore->Record["email"];
			}
		}
	}

	if ($module->isRegistered(MODULE_PARSER) && count($emaillist))
	{
		require_once ("./modules/parser/functions_misc.php");
		insertParserBan($emaillist);
	}

	return true;
}

/**
* Deletes given tickets
*/
function deleteTickets($ticketidlist, $depcheck = false)
{
	global $dbCore, $_SWIFT, $template;

	if (!_is_array($ticketidlist))
	{
		return false;
	}

	$strticketidlist = buildIN($ticketidlist);

	$template->loadLanguageSection("tickets_auditlogs", TEMPLATE_FILE);
	if ($depcheck == true)
	{
		$_assigns = getAssignedDepartments(MODULE_TICKETS);
	}

	$departmentidlist = $_ticketidlist = $_auditsql = array();
	$dbCore->query("SELECT `ticketid`, `ticketmaskid`, `departmentid`, `userid`, `subject`, `fullname`, `email` FROM `". TABLE_PREFIX ."tickets` WHERE `ticketid` IN (". $strticketidlist .");");
	while ($dbCore->nextRecord())
	{
		$_doauditlog = false;

		$departmentidlist[] = $dbCore->Record["departmentid"];
		if ($depcheck == true)
		{
			if (in_array($dbCore->Record["departmentid"], $_assigns))
			{
				$_ticketidlist[] = $dbCore->Record["ticketid"];

				$_doauditlog = true;
			}
		} else {
			$_ticketidlist[] = $dbCore->Record["ticketid"];
			$_doauditlog = true;
		}

		if ($_doauditlog)
		{
			$_auditsql[] = "('". intval($dbCore->Record["ticketid"]) ."', '". $dbCore->escape($_SWIFT["staff"]["staffid"]) ."', '". $dbCore->escape($dbCore->Record["departmentid"]) ."', '". $dbCore->escape($dbCore->Record["userid"]) ."', '". DATENOW ."', '". intval(LOG_STAFF) ."', '". intval(ACTION_DELETETICKET) ."','". $dbCore->escape(sprintf($_SWIFT["language"]["al_deleteticket"], iif($_SWIFT["settings"]["t_eticketid"]=="seq",$dbCore->Record["ticketid"], $dbCore->Record["ticketmaskid"]), htmlspecialchars($dbCore->Record["subject"]), htmlspecialchars($dbCore->Record["fullname"]), htmlspecialchars($dbCore->Record["email"]))) ."')";
		}
	}
	$strticketidlist = buildIN($_ticketidlist);

	// Build the ticketpostid list
	$ticketpostidlist = array();
	$dbCore->query("SELECT `ticketpostid`, `subject`, `contents` FROM `". TABLE_PREFIX ."ticketposts` WHERE `ticketid` IN (". $strticketidlist .");");
	while ($dbCore->nextRecord())
	{
		$ticketpostidlist[] = $dbCore->Record["ticketpostid"];
		$text .= $dbCore->Record["subject"]." ".$dbCore->Record["contents"]." ";
	}

	require_once ("./modules/tickets/functions_search.php");
	emptyTicketPostIndex($ticketpostidlist, $text);


	// Delete all data related to this ticket
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."tickets` WHERE `ticketid` IN (". $strticketidlist .");");
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."ticketposts` WHERE `ticketpostid` IN (". buildIN($ticketpostidlist) .");");
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."auditlogs` WHERE `ticketid` IN (". $strticketidlist .");");
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."ticketnotes` WHERE `typeid` IN (". $strticketidlist .") AND `notetype` = '". NOTE_TICKET ."';");
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."tickettimetrack` WHERE `ticketid` IN (". $strticketidlist .");");
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."ticketmergelog` WHERE `ticketid` IN (". $strticketidlist .");");
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."ticketmessageids` WHERE `ticketid` IN (". $strticketidlist .");");
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."ticketlabellinks` WHERE `ticketid` IN (". $strticketidlist .");");

	if (count($_auditsql))
	{
		$dbCore->query("INSERT INTO `". TABLE_PREFIX ."auditlogs` (`ticketid`, `staffid`, `departmentid`, `userid`, `dateline`, `logtype`, `actiontype`, `actionmsg`) VALUES ". implode(",", $_auditsql) .";");
	}

	// Get all attachments under this ticket
	$attachmentidlist = array();
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."attachments` WHERE `ticketid` IN (". $strticketidlist .");");
	while ($dbCore->nextRecord())
	{
		$attachmentidlist[] = $dbCore->Record["attachmentid"];
		if ($dbCore->Record["attachmenttype"] == ATTACHMENT_FILE)
		{
			// Attempt to delete this file
			@unlink("./files/".$_attachment["storefilename"]);
		}
	}
	// Delete all chunks
	if (count($attachmentidlist) != 0)
	{
		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."attachmentchunks` WHERE `attachmentid` IN (". buildIN($attachmentidlist) .");");
	}

	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."attachments` WHERE `ticketid` IN (". $strticketidlist .");");

	require_once ("./includes/functions_customfields.php");
	deleteCustomFieldValue(CUSTOMFIELD_USERTICKET, $_ticketidlist, false, $_ticketidlist);
	deleteCustomFieldValue(CUSTOMFIELD_STAFFTICKET, $_ticketidlist, false, $_ticketidlist);
	deleteCustomFieldValue(CUSTOMFIELD_STAFFUSERTICKET, $_ticketidlist, false, $_ticketidlist);

	//$this->alerts->raiseAlert(ALERT_DELETETICKET, array("ticketid" => $this->_ticket["ticketid"]));

	rebuildTicketCountCache($departmentidlist);

	rebuildLabelCountCache();

	return true;
}

/**
* Checks to see if a ticket is merged from a given ticket mask, if yes returns the *ticket id* (not mask) if not returns false
*/
function getMergedStatusFromMask($ticketmask)
{
	global $dbCore;

	$dbCore->query("SELECT `ticketid` FROM `". TABLE_PREFIX ."ticketmergelog` WHERE `oldticketmaskid` = '". $dbCore->escape($ticketmask) ."';");
	$dbCore->nextRecord();
	if (trim($dbCore->Record["ticketid"]) != "")
	{
		// Success!
		return $dbCore->Record["ticketid"];
	} else {
		return false;
	}
}

/**
* Checks for flood protection, compares against previous post.
*/
function checkFloodProtection($email, $subjecthash)
{
	global $dbCore, $_SWIFT;

	if ($_SWIFT["settings"]["t_enfp"] != 1)
	{
		parserDebug("WARNING: Flood Protection not enabled");
		return false;
	}

	parserDebug("NOTICE: Checking for flood protection, EmailHash: ".md5($email).", SubjectHash: ".$subjecthash);


	$_floodhash = $dbCore->queryFetch("SELECT `dateline` FROM `". TABLE_PREFIX ."floodhash` WHERE `emailhash` = '". $dbCore->escape(md5($email)) ."' ORDER BY `dateline` DESC LIMIT 1;");
	$timeline = DATENOW - intval($_SWIFT["settings"]["t_fthreshold"]);

	if (!empty($_floodhash["dateline"]))
	{
		parserDebug("NOTICE: Fetched last entry, date: ".date("d M Y h:i:s A", $_floodhash["dateline"]).", Email: ".$email);
	} else {
		parserDebug("NOTICE: No entry found for: ".$email);
	}


	// No Previous tickets under this email
	if (empty($_floodhash["dateline"]))
	{
		return false;
	}

	// Previous tickets under this email, check the threshold
	if ($_floodhash["dateline"] > $timeline)
	{
		parserDebug("NOTICE: Caught the threshold time, Thresholdtime: ". date("d M Y h:i:s A", $timeline).", Last ticket creation time: ".date("d M Y h:i:s A", $_floodhash["dateline"]));
		return true;
	}

	return false;
}

/**
* Checks to see if the email belongs to staff
*/
function isStaffEmail($email)
{
	global $_SWIFT;

	foreach ($_SWIFT["staffcache"] as $key=>$val)
	{
		if ($val["email"] == $email)
		{
			return true;
		}
	}

	return false;
}



/**
* Rebuilds the count for current labels
*/
function rebuildLabelCountCache()
{
	global $dbCore, $datastore;

	$_cache = array();

	$dbCore->query("SELECT COUNT(*) AS totalitems, `ticketlabelid` FROM `". TABLE_PREFIX ."ticketlabellinks` GROUP BY `ticketlabelid`;");
	while ($dbCore->nextRecord())
	{
		$_cache[$dbCore->Record["ticketlabelid"]] = intval($dbCore->Record["totalitems"]);
	}

	$datastore->update("labelcountcache", $_cache);
}

/**
* Rebuilds the counter cache for given department, ticketstatus
*/
function rebuildTicketCountCache($departmentidlist = false)
{
	global $dbCore, $_SWIFT, $datastore;

	if (!is_array($departmentidlist))
	{
		$departmentidlist = array();
	}
	$ticketstatusidlist = array();
	foreach ($_SWIFT["statuscache"] as $key=>$val)
	{
		$ticketstatusidlist[] = $val["ticketstatusid"];
	}

	$countlist = $prdepartmentidlist = $prticketstatusidlist = $prmergelist = array();
	if (count($departmentidlist)) {
		$dbCore->query("SELECT `departmentid`, `ticketstatusid`, COUNT(*) AS totalitems, MAX(`lastactivity`) AS lastactivity FROM `". TABLE_PREFIX ."tickets` GROUP BY `departmentid`, `ticketstatusid` HAVING `departmentid` IN (". buildIN($departmentidlist) .");");
	} else {
		$dbCore->query("SELECT `departmentid`, `ticketstatusid`, COUNT(*) AS totalitems, MAX(`lastactivity`) AS lastactivity FROM `". TABLE_PREFIX ."tickets` GROUP BY `departmentid`, `ticketstatusid`;");
	}

	while ($dbCore->nextRecord())
	{
		$prticketstatusidlist[] = array($dbCore->Record["departmentid"], $dbCore->Record["ticketstatusid"]);
		$prdepartmentidlist[] = $dbCore->Record["departmentid"];
		$prmergelist[] = $dbCore->Record["departmentid"]."-".$dbCore->Record["ticketstatusid"];
		if (!isset($_SWIFT["ticketcountcache"][$dbCore->Record["departmentid"]]["totaltickets"]))
		{
			$_SWIFT["ticketcountcache"][$dbCore->Record["departmentid"]]["totaltickets"] = 0;
		}
		$deplastactivity = &$_SWIFT["ticketcountcache"][$dbCore->Record["departmentid"]]["lastactivity"];
		if ($dbCore->Record["lastactivity"] > $deplastactivity)
		{
			$deplastactivity = $dbCore->Record["lastactivity"];
		}
		$_SWIFT["ticketcountcache"][$dbCore->Record["departmentid"]]["totaltickets"] += $dbCore->Record["totalitems"];
		$_SWIFT["ticketcountcache"][$dbCore->Record["departmentid"]][$dbCore->Record["ticketstatusid"]]["count"] = $dbCore->Record["totalitems"];
		$_SWIFT["ticketcountcache"][$dbCore->Record["departmentid"]][$dbCore->Record["ticketstatusid"]]["lastactivity"] = $dbCore->Record["lastactivity"];
	}

	// Now once we are done, we itterate through both departments and ticket statuses
	foreach ($departmentidlist as $key=>$val)
	{
		if (!in_array($val, $prdepartmentidlist))
		{
			$_SWIFT["ticketcountcache"][$val]["totaltickets"] = 0;
			$_SWIFT["ticketcountcache"][$val]["lastactivity"] = 0;
		}

		foreach ($ticketstatusidlist as $statuskey=>$statusval)
		{
			$mergetxt = $val."-".$statusval;
			if (!in_array($mergetxt, $prmergelist))
			{
				$_SWIFT["ticketcountcache"][$val][$statusval]["count"] = 0;
				$_SWIFT["ticketcountcache"][$val][$statusval]["lastactivity"] = 0;
			}
		}
	}

	$datastore->update("ticketcountcache", $_SWIFT["ticketcountcache"], true);
}

/**
* Check for merged ticket from a given ticket id
*/
function checkMergeStatusTicketID($ticketid)
{
	global $dbCore, $_SWIFT;

	$_merge = $dbCore->queryFetch("SELECT `ticketid` FROM `". TABLE_PREFIX ."ticketmergelog` WHERE `oldticketid` = '". $dbCore->escape($tickeitd) ."';");
	if (!empty($_merge["ticketid"]))
	{
		return $_merge["ticketid"];
	}

	return false;
}

/**
* Check for a merged ticket from a given ticket mask
*/
function checkMergeStatusTicketMask($ticketmaskid)
{
	global $dbCore, $_SWIFT;

	$_merge = $dbCore->queryFetch("SELECT `ticketid` FROM `". TABLE_PREFIX ."ticketmergelog` WHERE `oldticketmaskid` = '". $dbCore->escape($ticketmaskid) ."';");
	if (!empty($_merge["ticketid"]))
	{
		return $_merge["ticketid"];
	}

	return false;
}

/**
* Get the Ticket ID From Message ID
*/
function getTicketIDFromMessageID($messageid)
{
	global $dbCore, $_SWIFT;

	if (isset($_SWIFT["msgidcache"][$messageid]))
	{
		return $_SWIFT["msgidcache"][$messageid];
	}

	$_messageid = $dbCore->queryFetch("SELECT `messageid`, `ticketid` FROM `". TABLE_PREFIX ."ticketmessageids` WHERE `messageid` = '". $dbCore->escape($messageid) ."';");
	if (!empty($_messageid["ticketid"])) // We found a ticket through Message-ID! It Works! It Works!
	{
		$_SWIFT["msgidcache"][$messageid] = $_messageid["ticketid"];

		return $_messageid["ticketid"];
	}

	return false;
}

?>